<template>
  <div class="app-container flex-cloumn">
    <div class="wrapper">
      <div>
        <el-card class="card">
          <el-calendar ref="calendar">
            <template #dateCell="{data}">
              <div class="calendar-item" @click.stop="calendarOnClick(data)"
                   v-bind:class="{'calDay': calDayMap.get(data.day) === 1,'notCalDay':calDayMap.get(data.day) === 0}">
                <div class="calendar-time">
                  {{ data.day.split('-').slice(2).join('') }}
                </div>
                <div class="calendar-contentBox">
                  <div class="calendar-content remark-text" v-for="(item, index) in handleTradeCalendarList(data.day)"
                       v-show="index<2"
                       :key="index">
                    <el-tag > {{ item }}</el-tag>
                  </div>
                </div>
                <div class="calendar-content-amount" v-if="remindDayLength.get(data.day) >2">
                  <el-tag class="ml-2" type="warning">还有{{ remindDayLength.get(data.day) - 2 }}项</el-tag>
                </div>
              </div>
            </template>
          </el-calendar>
        </el-card>

      </div>
      <div>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>近31天事项</span>
            </div>
          </template>
          <div >
            <el-timeline>
              <el-timeline-item v-for="(item, index) in getTradeCalendarListProxy()" color="#0599D8" @click.native="calendarOnClick({day:item})" :timestamp="item" placement="top">
                <p v-for="(i, index) in handleTradeCalendarList(item)" >{{i}}</p>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </div>

    </div>

    <!-- 当日详细到期表 对话框 -->
    <el-dialog v-model=" remindOpen
            " :close-on-click-modal="false"  :title="remindTitle"
               width="70%">
      <div class="app-container  flex-cloumn">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="68px">
          <el-row :span="24">
            <el-col :span="6">
              <el-form-item label="合约编号">
                <el-input
                    v-model="queryParams.iCode"
                    placeholder="请输入合约编号"
                    clearable
                    size="small"
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="期权类型">
                <dictCombox v-model="queryParams.optionType" dictType="optionType" size="small"></dictCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="挂钩标的" prop="instrument">
                <underlyer clearable
                           size="small"
                           placeholder="挂钩标的" v-model="queryParams.instrument"></underlyer>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="本方账户" prop="accId">
                <baseCombox url="/trade/account/querySelfAccountCombox.action" clearable
                            size="small"
                            valueField="accId" labelField="accName" placeholder="本方账户"
                            v-model="queryParams.accId"></baseCombox>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row :span="24">

            <el-col :span="6">
              <el-form-item label="交易日期">
                <el-date-picker
                    v-model="queryParams.tradeDate"
                    placeholder="选择日期"
                    type="date"
                    value-format="YYYY-MM-DD">
                </el-date-picker>
              </el-form-item>

            </el-col>

            <el-col :span="6">
              <el-form-item label="行权方式" prop="exerciseType">
                <dictCombox v-model="queryParams.exerciseType" dictType="exerciseType" size="small"></dictCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="交易对手" prop="partyId">
                <baseCombox url="/trade/counterparty/queryCounterparty4Combox.action" clearable
                            size="small"
                            valueField="partyId" labelField="partyName" placeholder="交易对手"
                            v-model="queryParams.partyId"></baseCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="买卖方向" prop="payDirection">
                <dictCombox v-model="queryParams.payDirection" dictType="payDirection" size="small"></dictCombox>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :span="24">

            <el-col :span="6">
              <el-form-item label="期权状态" prop="eventStatus">
                <dictCombox v-model="queryParams.eventStatus" dictType="durationStatus" size="small"></dictCombox>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button icon="Search" size="small" style="margin: 5px 5px" type="primary" @click="handleQuery">
                  搜索
                </el-button>
                <el-button icon="Search" size="small" style="margin: 5px 5px" type="primary"
                           @click="goToTradeBalance">
                  跳转
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>


        <xTable ref="refTradeBalanceTable" v-loading="loading" :data="tradeList"
                @selection-change="handleTradeSelectionChange"
                class="tableDragger_form"
                border
                fit
                multiple="false"
                refId="refTradeBalanceTable">

          <template #columList>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="序号" type="index" width="60">
            </el-table-column>
            <el-table-column align="center" label="产品编号" prop="extTradeId" width="200" />
            <el-table-column align="center" label="合约编号" prop="iCode" width="200" />
            <el-table-column align="center" label="期权类型" prop="productType" width="auto"><template #default="scope"> <dict-tag spVal="*" :options="optionType" :value="scope.row.productType"/></template></el-table-column>
            <el-table-column align="center" label="交易日期" prop="tradeDate" width="auto"></el-table-column>
            <el-table-column :show-overflow-tooltip="true" align="center" label="标的代码" prop="uICode" width="auto"/>
            <el-table-column align="center" label="标的名称" prop="uIName" width="100px"/>
            <el-table-column v-if="false" align="center" label="资产类型" prop="uAType" width="auto"/>
            <el-table-column v-if="false" align="center" label="市场类型" prop="uMType" width="auto"/>
            <el-table-column align="center" label="买卖方向" prop="payDirection" width="auto"> <template #default="scope"> <dict-tag :options="payDirection" :value="scope.row.payDirection"/> </template> </el-table-column>
            <el-table-column align="center" label="涨跌类型" prop="optionType" width="auto"> <template #default="scope"> <dict-tag :options="callPut" :value="scope.row.optionType"/>  </template></el-table-column>
            <el-table-column align="center" label="行权方式" prop="exerciseType" width="auto"><template #default="scope"><dict-tag :options="exerciseType" :value="scope.row.exerciseType"/></template></el-table-column>
            <el-table-column :formatter="formartTableP2" align="right" label="高行权价(元)" prop="strikePrice" width="100px"/>
            <el-table-column :formatter="formartTableP2" align="right" label="低行权价(元)" prop="lowStrikePrice" width="100px"/>
            <el-table-column :formatter="formartTablePercentP2" align="right" label="收益率1(%)" prop="yield1" width="100px"/>
            <el-table-column :formatter="formartTablePercentP2" align="right" label="收益率2(%)" prop="yield2" width="100px"/>
            <el-table-column :formatter="formartTablePercentP2" align="right" label="收益率3(%)" prop="yield3" width="100px"/>
            <el-table-column :formatter="formartTableP2" align="right" label="障碍价1(元)" prop="triggerPrice1" width="100px"/>
            <el-table-column :formatter="formartTableP2" align="right" label="障碍价2(元)" prop="triggerPrice2" width="100px"/>
            <el-table-column :formatter="(row, column, cellValue)=>{return Boolean(cellValue=='1')?'是':'否'}" align="right" label="期权费年化" prop="frontOptionFeeYear" width="120px"/>
            <el-table-column :formatter="formartEmptyTableP2" align="right" label="期权费率(%)" prop="frontOptionFeeRate" width="100px"/>
            <el-table-column :formatter="formartEmptyTableP2" align="right" label="期权费(元)" prop="frontOptionFee" width="100px"/>
            <el-table-column align="center" label="期权费支付日" prop="frontOptionFeePaydate" width="120px"/>

            <el-table-column :formatter="(row, column, cellValue)=>{return Boolean(cellValue=='1')?'是':'否'}" align="right" label="前端费年化" prop="frontFeeYear" width="120px"/>
            <el-table-column :formatter="formartEmptyTableP2" align="right" label="前端费率(%)" prop="frontFeeRate" width="100px"/>
            <el-table-column :formatter="formartEmptyTableP2" align="right" label="前端费(元)" prop="frontFee" width="100px"/>
            <el-table-column align="center" label="前端费支付日" prop="frontFeePaydate" width="100px"/>
            <el-table-column align="center" label="起始日" prop="issueDate" width="100px"/>
            <el-table-column align="center" label="到期日" prop="maturityDate" width="100px"/>
            <el-table-column align="center" label="到期支付日" prop="paymentDate" width="100px"/>
            <el-table-column :formatter="formartTableP2" align="right" label="提前终止费用(元)" prop="terminateFee" width="120px"/>
            <el-table-column :formatter="formartTableP2" align="right" label="期初价格" prop="calcPrice" width="100px"/>
            <el-table-column :formatter="formartTableP2" align="right" label="名义本金(元)" prop="volume" width="100px"/>
            <el-table-column :formatter="formartTablePercentP2" align="right" label="参与率1(%)" prop="participationRate1" width="100px"/>
            <el-table-column :formatter="formartTablePercentP2" align="right" label="参与率2(%)" prop="participationRate2" width="100px"/>
            <!--            <el-table-column :formatter="formartTablePercentP2" align="right" label="固定利率(%)" prop="fixedRate" width="100px"/>-->
            <el-table-column align="center" label="期权状态" prop="eventStatus" width="auto">
              <template #default="scope">
                <dict-tag :options="durationStatus" :value="scope.row.eventStatus"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="交易对手" prop="partyName" width="auto"/>
            <el-table-column align="center" label="本方账户" prop="accName" width="100px"/>
            <el-table-column align="center" label="计算日期" prop="calcDate" width="80">
              <template #default="scope">
                {{ scope.row.calcDate == null ? '未估值' : scope.row.calcDate }}
              </template>
            </el-table-column>
            <!--            <el-table-column :formatter="formartTablePercentP2" align="right" label="收益率(%)" prop="yield"-->
            <!--                             width="85"/>-->
            <el-table-column :formatter="formartTablePercentP2" align="right" label="已实现收益率(%)"
                             prop="realizedYield"
                             width="110"/>
            <!--            <el-table-column :formatter="formartTablePercentP2" align="right" label="历史盈亏率(%)" prop="hisYield"-->
            <!--                             width="110"/>-->

            <el-table-column :formatter="formartTableP2" align="right" label="浮动盈亏(元)" prop="plFloat"
                             width="110"/>
            <el-table-column :formatter="formartTableP4" align="right" label="npv" prop="npv" width="110"/>
            <el-table-column :formatter="formartTableP4" align="right" label="delta" prop="delta" width="110"/>
            <el-table-column :formatter="formartTableP4" align="right" label="deltacash" prop="cashDelta"
                             width="130"/>
            <el-table-column :formatter="formartTableP4" align="right" label="gamma" prop="gamma" width="110"/>
            <el-table-column :formatter="formartTableP4" align="right" label="gammacash" prop="cashGamma"
                             width="130"/>
            <el-table-column :formatter="formartTableP4" align="right" label="theta" prop="theta" width="110"/>
            <el-table-column :formatter="formartTableP4" align="right" label="vega" prop="vega" width="110"/>
            <el-table-column :formatter="formartTableP4" align="right" label="rho" prop="rho" width="110"/>
            <!-- <el-table-column align="center">
              <template #default="scope">
                <el-button size="small" @click="openDetail(scope.$index, scope.row)"
                >详情
                </el-button>
              </template>
            </el-table-column> -->
          </template>
        </xTable>

        <pagination
            v-show="total > 0"
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNum"
            :total="total"
            @pagination="getTradeList"
        />


      </div>
    </el-dialog>
  </div>
</template>
<!--提醒日历-->
<script setup name="Remind">
import {
  query30DaysTradeCalendar,
  queryAllTradeCalendar,
  getTodayTrade4OtcOptionByPage
} from "@/api/remind/calendar";
import {queryTradeCalendarDates} from "@/api/trade/tradecalendar";

const {proxy} = getCurrentInstance();
const {
  callPut,
  M_TYPE,
  A_TYPE,
  CURRENCY,
  optionType,
  priceType,
  exerciseType,
  tradeType,
  optionTypePp,
  payDirection,
  durationStatus,
} = proxy.useDict("callPut","M_TYPE", "A_TYPE", "CURRENCY", "optionType", "optionTypePp", "priceType", "exerciseType", "tradeType", "durationStatus", "payDirection");

const tradeCalendarList = ref([]);

const remindTitle = ref('当日所有提醒交易');
const remindOpen = ref(false);

const tradeList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const router = useRouter();
const total = ref(0);
//索引
const indexs = ref([]);
//数据
const rows = ref([]);

const single = ref(true);
const multiple = ref(true);

const remindDayLength = reactive(new Map());
const calDayMap = reactive(new Map());


const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    iCode: undefined,
    iCodes: undefined,
    iCodesArr: undefined,
    optionType: undefined,
    instrument: undefined,
    tradeDate: undefined,
    partyId: undefined,
    accId: undefined,
    priceType: 'DP_CLOSE',

    eventStatus: undefined,
    payDirection: undefined,
    exerciseType: ''
  }
});

const {queryParams} = toRefs(data);

/** 查询提醒日历列表 */
function getTradeCalendarList() {
  query30DaysTradeCalendar().then(response => {
    tradeCalendarList.value = response;
  });
}
/** 获取当月事件的交易日 */
function getTradeCalendarListProxy() {
  return Array.from(new Set(tradeCalendarList.value.sort((a,b)=>{return new Date(a.REMIND_DATE) - new Date(b.REMIND_DATE)}).map(item=>item.REMIND_DATE)))
}
/** 查询交易列表 */
function getTradeList() {
  loading.value = true;
  getTodayTrade4OtcOptionByPage(queryParams.value).then(response => {
    tradeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;

  getTradeList();
}

function goToTradeBalance() {
  //跳转前关闭dialog,否则会给html加 style：overflow:hidden;
  remindOpen.value = false;
  var queryParam = {
    pageNum: 1,
    pageSize: 20,
    iCodes: undefined,
  }
  var iCodesArry = [];
  if (rows.value.length > 0) {
    rows.value.forEach(element => {
      iCodesArry.push(element.iCode)
    });
    queryParam.iCodes = JSON.stringify(iCodesArry);
  } else {
    tradeList.value.forEach(element => {
      iCodesArry.push(element.iCode)
    });
    queryParam.iCodes = JSON.stringify(iCodesArry);
  }
  router.push({path: '/TradeManage/tradeBalance', query: queryParam})
}

const handleTradeCalendarList = (v) => {
  let res = [];
  if (!proxy.lsh.isNull(tradeCalendarList.value)) {
    for (let index = 0; index < tradeCalendarList.value.length; index++) {
      if (tradeCalendarList.value[index].REMIND_DATE == v) {
        res.push(tradeCalendarList.value[index].REMIND_MSG);
      }
    }
  }
  remindDayLength.set(v, res.length);
  return res;
}

function getDayICodes(day) {
  var iCodes = [];
  if (!proxy.lsh.isNull(tradeCalendarList.value)) {
    for (let index = 0; index < tradeCalendarList.value.length; index++) {
      if (tradeCalendarList.value[index].REMIND_DATE == day) {
        iCodes.push(tradeCalendarList.value[index].I_CODE);
      }
    }
  }
  return iCodes;
}


onMounted(() => {
  setTimeout(() => {
    loading.value = false;
  }, 300);
})


function calendarOnClick(data) {
  //直接遍历 tradeCalendarList 将当天到期的icodes都存起来
  tradeList.value = [];
  queryParams.value.iCodesArr = getDayICodes(data.day);
  remindTitle.value =  proxy.$moment(data.day).format('YYYY-MM-DD') + '_交易提醒'
  if (queryParams.value.iCodesArr.length > 0) {
    remindOpen.value = true;
  } else {
    return;
  }
  if (!proxy.lsh.isEmpty(queryParams.value.iCodesArr) && !proxy.lsh.isNull(queryParams.value.iCodesArr) && queryParams.value.iCodesArr != undefined) {
    queryParams.value.iCodes = JSON.stringify(queryParams.value.iCodesArr);
    getTradeList();
  }
}


/**
 *
 *  多选框选中数据
 * */
function handleTradeSelectionChange(selection) {
  if (selection.length == 0) {
    indexs.value = [];
    rows.value = [];
  } else {
    indexs.value = selection.map(item => item.index);
    rows.value = selection.map(item => item);
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  if (selection.length == 1) {
    return;
  }
  if (selection.length != 1) {

  }
}

/** 查询交易日历配置列表 */
function getTradeCalendarDatesList(params) {
  queryTradeCalendarDates(params).then(response => {
    response.forEach(element => {
      calDayMap.set(element.CAL_DAY, element.CAL_FLAG);
    })

  });
}

getTradeCalendarList();
getTradeCalendarDatesList({
  calCode: 'CHINA_EX',
});

</script>


<style lang="scss" scoped>

.wrapper {
  display: inline-grid;
  grid-template-columns: 7fr 2fr ;
  grid-column-gap: 10px;
}
.card {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow-y:scroll;
  font-size: 14px;
  border: 0
}


::v-deep .el-timeline-item__timestamp.is-top {
  position: absolute;
  left: -78px;
  color: #0599D8;
}
::v-deep .el-timeline {
  padding-left: 100px;
}
/**修改全局的滚动条*/
/**滚动条的宽度*/
::-webkit-scrollbar {
  width: 8px;

}
//滚动条的滑块
::-webkit-scrollbar-thumb {
  background-color: #eaecf1;
  border-radius: 3px;
}

.card  ::v-deep .el-card__header {
  position: sticky;
  opacity: 1;
  top: 0;
  z-index: 999;
  font-size: 18px !important;
  padding: 12px 0px 18px 18px !important;
  color:  #fff !important;
  min-height: 50px !important;
  font-weight: bold !important;
  font-family: PingFangSC-Medium;
  text-align: left !important;
  height: auto !important;
  background-image: url("@/assets/images/card_header.png");
  background-position:  666px;
}
.card ::v-deep .el-card__body{
  z-index: unset;
}
.card-header span{
  border-left: 3px solid #0599D9;
  padding-left: 10px;
  color:  #fff !important;
}
::v-deep .el-calendar__header{
  background-image: url("@/assets/images/card_header.png");
  background-position: right 666px;
  //background-color: lightgray;
}
::v-deep .el-button--small{
  background: rgba(255,255,255,0.10);
  border: 1px solid rgba(255,255,255,0.10);
  border-radius: 4px 0 0 4px;
  color: #fff;
}
::v-deep .el-button--small:hover {
  background: #0599D9;
  border-color: #0599D9;
  color: #fff;
}

::v-deep .el-calendar__title{
  color: #FFFFFF;
}
.remark-text {
  font-size: 10px;
  //color: red;
}

.calendar-item {
  border: 1px solid rgba(20,27,40,0.15);
  border-radius: 4px;
  padding-top: 8px;
  flex-direction: column;
  text-align: center;
  height: 100%;
}

.calendar-time {
  height: 16px;
  line-height: 16px;
}

.el-dialog-div{
  height: 75vh;
  overflow: auto;
  padding: 10px 10px;
}
.el-dialog-table{
  height: 60vh;
}

.calendar-contentBox {
  text-align: center;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.calendar-content {
  margin: 6px;
  height: 16px;
  line-height: 16px;
}

.calendar-content-amount {

  font-size: 5px;
  color: #666;
  margin-top: 2px;
  height: 16px;
  line-height: 16px;
}

.calDay {
  //background-color: #e5f1fd;
  // background-color: blue;
  // background-color: aqua;
}

.notCalDay {
  background-color: #f9f9f9;

}


</style>

<style>

.el-calendar {
  --el-calendar-cell-width: 121px;
  --el-calendar-border: var(--el-table-border, 0px solid var(--el-border-color-lighter));
}

.el-calendar-table thead {
  background-color: #efefef;
  font-weight: bold;
  color: black;
}

.el-calendar__body {
  padding: 0;
}

.el-calendar .calendar-item {
  padding-top: 20px;
  font-size: 20px;
}

.el-calendar__header {
  font-size: 20px;
  font-weight: bold;
}


.el-calendar__header .el-button {
  height: 30px;
}


.el-calendar-table {
  /*background-color: white;*/
}

.el-calendar-table .el-calendar-day {
  padding: 3px;
}

.tableDragger_form {
  flex: 1 0 50vh;
}

</style>
